package com.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;

import com.utils.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.annotation.IgnoreAuth;
import com.entity.OrdersEntity;
import com.service.OrdersService;

import com.entity.SaishipiaowuEntity;
import com.entity.view.SaishipiaowuView;

import com.service.SaishipiaowuService;
import com.service.TokenService;
import com.utils.PageUtils;
import com.utils.R;
import com.utils.MPUtil;
import com.utils.MapUtils;
import com.utils.CommonUtil;
import java.io.IOException;
import com.service.StoreupService;
import com.entity.StoreupEntity;
/**
 * 赛事票务
 * 后端接口
 * @author
 * @email
 * @date 2024-03-11 17:58:32
 */
@RestController
@RequestMapping("/saishipiaowu")
public class SaishipiaowuController {
    @Autowired
    private SaishipiaowuService saishipiaowuService;

    @Autowired
    private StoreupService storeupService;

    @Autowired
    private OrdersService ordersService;

    /**
     * 后端列表
     */
    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params,SaishipiaowuEntity saishipiaowu,
                  @RequestParam(required = false) Double pricestart,
                  @RequestParam(required = false) Double priceend,
                  HttpServletRequest request){
        EntityWrapper<SaishipiaowuEntity> ew = new EntityWrapper<SaishipiaowuEntity>();
        if(pricestart!=null) ew.ge("price", pricestart);
        if(priceend!=null) ew.le("price", priceend);

        PageUtils page = saishipiaowuService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, saishipiaowu), params), params));

        return R.ok().put("data", page);
    }

    /**
     * 前端列表
     */
    @IgnoreAuth
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params,SaishipiaowuEntity saishipiaowu,
                  @RequestParam(required = false) Double pricestart,
                  @RequestParam(required = false) Double priceend,
                  HttpServletRequest request){
        EntityWrapper<SaishipiaowuEntity> ew = new EntityWrapper<SaishipiaowuEntity>();
        if(pricestart!=null) ew.ge("price", pricestart);
        if(priceend!=null) ew.le("price", priceend);

        PageUtils page = saishipiaowuService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, saishipiaowu), params), params));
        return R.ok().put("data", page);
    }



    /**
     * 列表
     */
    @RequestMapping("/lists")
    public R list( SaishipiaowuEntity saishipiaowu){
        EntityWrapper<SaishipiaowuEntity> ew = new EntityWrapper<SaishipiaowuEntity>();
        ew.allEq(MPUtil.allEQMapPre( saishipiaowu, "saishipiaowu"));
        return R.ok().put("data", saishipiaowuService.selectListView(ew));
    }

    /**
     * 查询
     */
    @RequestMapping("/query")
    public R query(SaishipiaowuEntity saishipiaowu){
        EntityWrapper< SaishipiaowuEntity> ew = new EntityWrapper< SaishipiaowuEntity>();
        ew.allEq(MPUtil.allEQMapPre( saishipiaowu, "saishipiaowu"));
        SaishipiaowuView saishipiaowuView =  saishipiaowuService.selectView(ew);
        return R.ok("查询赛事票务成功").put("data", saishipiaowuView);
    }

    /**
     * 后端详情
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
        SaishipiaowuEntity saishipiaowu = saishipiaowuService.selectById(id);
        saishipiaowu.setClicktime(new Date());
        saishipiaowuService.updateById(saishipiaowu);
        saishipiaowu = saishipiaowuService.selectView(new EntityWrapper<SaishipiaowuEntity>().eq("id", id));
        return R.ok().put("data", saishipiaowu);
    }

    /**
     * 前端详情
     */
    @IgnoreAuth
    @RequestMapping("/detail/{id}")
    public R detail(@PathVariable("id") Long id){
        SaishipiaowuEntity saishipiaowu = saishipiaowuService.selectById(id);
        saishipiaowu.setClicktime(new Date());
        saishipiaowuService.updateById(saishipiaowu);
        saishipiaowu = saishipiaowuService.selectView(new EntityWrapper<SaishipiaowuEntity>().eq("id", id));
        return R.ok().put("data", saishipiaowu);
    }




    /**
     * 后端保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody SaishipiaowuEntity saishipiaowu, HttpServletRequest request){
        //ValidatorUtils.validateEntity(saishipiaowu);
        saishipiaowuService.insert(saishipiaowu);
        return R.ok();
    }

    /**
     * 前端保存
     */
    @RequestMapping("/add")
    public R add(@RequestBody SaishipiaowuEntity saishipiaowu, HttpServletRequest request){
        //ValidatorUtils.validateEntity(saishipiaowu);
        saishipiaowuService.insert(saishipiaowu);
        return R.ok();
    }



    /**
     * 修改
     */
    @RequestMapping("/update")
    @Transactional
    public R update(@RequestBody SaishipiaowuEntity saishipiaowu, HttpServletRequest request){
        //ValidatorUtils.validateEntity(saishipiaowu);
        saishipiaowuService.updateById(saishipiaowu);//全部更新
        return R.ok();
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids){
        saishipiaowuService.deleteBatchIds(Arrays.asList(ids));
        return R.ok();
    }


    /**
     * 前端智能排序
     */
    @IgnoreAuth
    @RequestMapping("/autoSort2")
    public R autoSort(@RequestParam Map<String, Object> params,SaishipiaowuEntity saishipiaowu, HttpServletRequest request,String pre){
        EntityWrapper<SaishipiaowuEntity> ew = new EntityWrapper<SaishipiaowuEntity>();
        Map<String, Object> newMap = new HashMap<String, Object>();
        Map<String, Object> param = new HashMap<String, Object>();
        Iterator<Map.Entry<String, Object>> it = param.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String key = entry.getKey();
            String newKey = entry.getKey();
            if (pre.endsWith(".")) {
                newMap.put(pre + newKey, entry.getValue());
            } else if (StringUtils.isEmpty(pre)) {
                newMap.put(newKey, entry.getValue());
            } else {
                newMap.put(pre + "." + newKey, entry.getValue());
            }
        }
        params.put("sort", "clicktime");
        params.put("order", "desc");
        PageUtils page = saishipiaowuService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, saishipiaowu), params), params));
        return R.ok().put("data", page);
    }


    /**
     * 协同算法（按用户购买推荐）
     */
    @RequestMapping("/autoSort")
    public R autoSort2(@RequestParam Map<String, Object> params,SaishipiaowuEntity saishipiaowu, HttpServletRequest request){
        String userId = request.getSession().getAttribute("userId").toString();
        String goodtypeColumn = "piaowuleixing";
        List<OrdersEntity> orders = ordersService.selectList(new EntityWrapper<OrdersEntity>().eq("userid", userId).eq("tablename", "saishipiaowu").orderBy("addtime", false));
        List<String> goodtypes = new ArrayList<String>();
        Integer limit = params.get("limit")==null?10:Integer.parseInt(params.get("limit").toString());
        List<SaishipiaowuEntity> saishipiaowuList = new ArrayList<SaishipiaowuEntity>();
        //去重
        List<OrdersEntity> ordersDist = new ArrayList<OrdersEntity>();
        for(OrdersEntity o1 : orders) {
            boolean addFlag = true;
            for(OrdersEntity o2 : ordersDist) {
                if(o1.getGoodid()==o2.getGoodid() || o1.getGoodtype().equals(o2.getGoodtype())) {
                    addFlag = false;
                    break;
                }
            }
            if(addFlag) ordersDist.add(o1);
        }
        if(ordersDist!=null && ordersDist.size()>0) {
            for(OrdersEntity o : ordersDist) {
                saishipiaowuList.addAll(saishipiaowuService.selectList(new EntityWrapper<SaishipiaowuEntity>().eq(goodtypeColumn, o.getGoodtype())));
            }
        }
        EntityWrapper<SaishipiaowuEntity> ew = new EntityWrapper<SaishipiaowuEntity>();
        params.put("sort", "id");
        params.put("order", "desc");
        PageUtils page = saishipiaowuService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, saishipiaowu), params), params));
        List<SaishipiaowuEntity> pageList = (List<SaishipiaowuEntity>)page.getList();
        if(saishipiaowuList.size()<limit) {
            int toAddNum = (limit-saishipiaowuList.size())<=pageList.size()?(limit-saishipiaowuList.size()):pageList.size();
            for(SaishipiaowuEntity o1 : pageList) {
                boolean addFlag = true;
                for(SaishipiaowuEntity o2 : saishipiaowuList) {
                    if(o1.getId().intValue()==o2.getId().intValue()) {
                        addFlag = false;
                        break;
                    }
                }
                if(addFlag) {
                    saishipiaowuList.add(o1);
                    if(--toAddNum==0) break;
                }
            }
        } else if(saishipiaowuList.size()>limit) {
            saishipiaowuList = saishipiaowuList.subList(0, limit);
        }
        page.setList(saishipiaowuList);
        return R.ok().put("data", page);
    }








}
